package com.ldk.admin.interceptors;

import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.ldk.admin.constants.CONFIG;
import com.ldk.admin.constants.SESSION;
import com.ldk.base.framework.util.ConfigUtil;
import com.ldk.base.framework.util.ConvertUtil;
import com.ldk.base.framework.util.PropertiesUtil;
import com.ldk.base.framework.util.push.JPushDispatcher;

public class ConfigInterceptor implements HandlerInterceptor {
	
	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		//系统配置
		if (request.getSession().getAttribute("configs") == null) {
			try {
				String cfgPath = CONFIG.DEBUG ? 
						this.getClass().getResource("/").getPath() + "/config_debug.properties" : 
						this.getClass().getResource("/").getPath() + "/config.properties";
				Properties cfgProps = PropertiesUtil.read(cfgPath);
				request.getSession().setAttribute(SESSION.CONFIGS, cfgProps);
				// 设置配置属性到系统属性中
				ConfigUtil.GetInstance().setConfig(cfgProps);
			} catch (Exception e) {
				logger.error(e.getMessage());
			}
		}
		//推送配置
		if(request.getSession().getAttribute("push") == null){
			try{
				String cfgPath = this.getClass().getResource("/").getPath() + "/push.properties";
				Properties cfgProps = PropertiesUtil.read(cfgPath);
				request.getSession().setAttribute("push", cfgProps);
				//push参数配置
				String startup = PropertiesUtil.getProperty(cfgProps, "startup");
				Boolean usePush = ConvertUtil.parseBoolean(startup);
				if(usePush){
					String client_masterSecret = PropertiesUtil.getProperty(cfgProps, "client_masterSecret");
					String client_appKey  = PropertiesUtil.getProperty(cfgProps, "client_appKey");
					String server_masterSecret = PropertiesUtil.getProperty(cfgProps, "server_masterSecret");
					String server_appKey  = PropertiesUtil.getProperty(cfgProps, "server_appKey");
					//配置推送
					JPushDispatcher.getInstance().register("client", client_masterSecret, client_appKey, CONFIG.APNS_PRODUCTION);
					JPushDispatcher.getInstance().register("server", server_masterSecret, server_appKey, CONFIG.APNS_PRODUCTION);
				}
			}
			catch(Exception e){
				logger.error(e.getMessage());
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}

}
